package userServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import routeDao.RouteDao;
import routeEntity.Route;
import routeImplment.RouteImplment;
import ticketDao.TicketDao;
import ticketEntity.Ticket;
import ticketImplment.TicketImplment;
import userEntity.User;
import userImplment.UserImplement;

/**
 * Servlet implementation class QueryBook
 */
public class QueryBook extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QueryBook() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String bookRouteId1 = request.getParameter("BookRouteId");
		int bookRouteId=Integer.parseInt(bookRouteId1);//获得所购票的路线Rid
		RouteDao routeImplment=new RouteImplment();
		TicketDao ticketImplment=new TicketImplment();
		UserImplement userImplement=new UserImplement();//定义实现类
		User user;
		Route route=routeImplment.RouteQuery(bookRouteId);//获得所购路线对象
		HttpSession session=request.getSession();
		PrintWriter out=response.getWriter();
		if(session.getAttribute("user")!=null){
			 user=(User) session.getAttribute("user");// 如果已经登录则获得需购票的用户对象，否则提示
			if(user.getBalance()>=route.getSeatPrice()) {
				userImplement.Pay(user.getId(), -route.getSeatPrice());//如果用户够钱在用户余额里扣钱，否则提示
				if(route.getSeatNumber()>0) {
					routeImplment.SubSeatNumber(bookRouteId);// 如果余票充足，余票减一，否则提示
					if(ticketImplment.AddTicket(user, route)) {
						user.setBalance(userImplement.Query(user.getId()).getBalance());
						session.setAttribute("user",user);  //更新用户信息到session
						out.write("true");
					}else {
                        out.write("false");
                    }
				}else {
					    out.write("noSeat");
				}
			}else {
                  out.write("noMoney");
            }
		}else {
			out.write("noLogin");
		}


	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
